package com.efounder.adapter;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.RequestOptions;
import com.efounder.bean.CartListBean;
import com.efounder.bean.GoodSkusBean;
import com.efounder.bean.UpdateCartBadgeEvent;
import com.efounder.chat.utils.LXGlideImageLoader;
import com.efounder.constant.EnvironmentVariable;
import com.efounder.mobilemall.R;
import com.efounder.utils.MallRequestUtil;
import com.efounder.utils.MyMathUtil;
import com.efounder.view.AmountView;
import com.pansoft.openplanet.util.TCMathUtil;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import static com.efounder.utils.MallRequestUtil.CART_ADD_OR_DELETE_URL;

/**
 * Created by will on 18-1-19.
 *
 * @author will
 */

public class CartExpandableAdapter extends BaseExpandableListAdapter {

    private List<CartListBean.MyshopcartBean> cartStores;
    private Context mContext;
    private int totalCount;
    private double totalPrice;
    private double totalTax;

    private OnAllCheckedBoxNeedChangeListener onAllCheckedBoxNeedChangeListener;
    private OnGoodsCheckedChangeListener onGoodsCheckedChangeListener;
    private OnCheckHasGoodsListener onCheckHasGoodsListener;
    private OnEditingTvChangeListener onEditingTvChangeListener;
    private OnGoodsDeleteChangeListener onGoodsDeleteChangeListener;
    private OnAdapterAmountChangeListener onAmountChangeListener;
    private boolean isFirst = true;

    public CartExpandableAdapter(List<CartListBean.MyshopcartBean> cartStores, Context mContext) {
        this.cartStores = cartStores;
        this.mContext = mContext;
    }

    public void deleteGoodsUpdate(List<CartListBean.MyshopcartBean> cartStores) {
        this.cartStores = cartStores;
        if (isAllGoodInvalid()) {
            if(onEditingTvChangeListener!=null){
                onEditingTvChangeListener.onEditingTvChange(false);
            }
        }
        notifyDataSetChanged();
    }

    @Override
    public int getGroupCount() {
        return cartStores.size();
    }

    @Override
    public int getChildrenCount(int i) {
        return cartStores.get(i).getGoods().size();
    }

    @Override
    public Object getGroup(int i) {
        return cartStores.get(i);
    }

    @Override
    public Object getChild(int i, int i1) {
        return cartStores.get(i).getGoods().get(i1);
    }

    @Override
    public long getGroupId(int i) {
        return i;
    }

    @Override
    public long getChildId(int i, int i1) {
        return i1;
    }

    @Override
    public boolean hasStableIds() {
        return true;
    }

    @Override
    public View getGroupView(final int i, boolean b, View view, ViewGroup viewGroup) {
        GroupViewHolder groupViewHolder;
        if (view == null) {
            view = LayoutInflater.from(mContext).inflate(R.layout.cart_item_parent, null);
            groupViewHolder = new GroupViewHolder();
            groupViewHolder.storeName = view.findViewById(R.id.tv_store_name);
            groupViewHolder.storeCheck = view.findViewById(R.id.id_cb_select_parent);
            groupViewHolder.ivShopIcon = view.findViewById(R.id.iv_shop_icon);
            view.setTag(groupViewHolder);
        } else {
            groupViewHolder = (GroupViewHolder) view.getTag();
        }
        groupViewHolder.storeName.setText(cartStores.get(i).getMallShop().getShopName());
        final boolean nowCheck = cartStores.get(i).isSelect();
        groupViewHolder.storeCheck.setChecked(dealOneParentAllChildIsChecked(i));

        if (isShopItemAllInvalid(i)) {
            groupViewHolder.storeCheck.setEnabled(false);
            groupViewHolder.storeCheck.setChecked(false);
        } else {
            groupViewHolder.storeCheck.setEnabled(true);
        }
        LXGlideImageLoader.getInstance().displayRoundCornerImage(mContext, groupViewHolder.ivShopIcon,
                cartStores.get(i).getMallShop().getShopBrandlog(), R.drawable.shop, R.drawable.shop, 20);
        groupViewHolder.storeCheck.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                setupOneParentAllChildChecked(!nowCheck, i);
                onAllCheckedBoxNeedChangeListener.onCheckedBoxNeedChange(dealAllParentIsChecked());
            }
        });
        return view;
    }

    @Override
    public View getChildView(final int groupPosition, final int childPosition, boolean b, View view, ViewGroup viewGroup) {
        ChildViewHolder childViewHolder = null;
        if (view == null) {
            view = LayoutInflater.from(mContext).inflate(R.layout.cart_item_child, null);
            childViewHolder = new ChildViewHolder();
            childViewHolder.ivImg = (ImageView) view.findViewById(R.id.id_iv_logo);
            childViewHolder.tvTitle = (TextView) view.findViewById(R.id.tv_item_title);
            childViewHolder.tvPrice = (TextView) view.findViewById(R.id.tv_item_price);
            childViewHolder.tvNumber = (TextView) view.findViewById(R.id.item_count);
//            childViewHolder.benefit = (TextView) view.findViewById(R.id.tv_benefit);
            childViewHolder.itemCheck = (CheckBox) view.findViewById(R.id.id_cb_select_child);
            childViewHolder.tvDesc = view.findViewById(R.id.tv_item_desc);
//            childViewHolder.ivDelete = (ImageView) view.findViewById(R.id.iv_delete);
            childViewHolder.amountView = (AmountView) view.findViewById(R.id.amount_view);
            childViewHolder.invalidLayer = view.findViewById(R.id.view_invalid_layer);
            childViewHolder.tvInvalid = view.findViewById(R.id.tv_invalid);
            view.setTag(childViewHolder);
        } else {
            childViewHolder = (ChildViewHolder) view.getTag();
        }
        final CartListBean.MyshopcartBean.GoodsBean cartItem = cartStores.get(groupPosition).getGoods().get(childPosition);

        //商品失效
        if (cartItem.getGood().getGoodStatus() == 0 ||
                cartItem.getGood().getGoodSkus().get(0).getStockNumber() <= 0) {
            childViewHolder.invalidLayer.setVisibility(View.VISIBLE);
            childViewHolder.itemCheck.setEnabled(false);
            childViewHolder.tvPrice.setTextColor(mContext.getResources().getColor(R.color.black_text_color));
            childViewHolder.tvInvalid.setVisibility(View.VISIBLE);
            childViewHolder.tvNumber.setVisibility(View.GONE);
        } else {
            childViewHolder.invalidLayer.setVisibility(View.GONE);
            childViewHolder.itemCheck.setEnabled(true);
            childViewHolder.tvPrice.setTextColor(mContext.getResources().getColor(R.color.mall_color_blue));
            childViewHolder.tvInvalid.setVisibility(View.GONE);
            childViewHolder.tvNumber.setVisibility(View.VISIBLE);
        }

        //编辑，里面加入失效商品判断
        if (cartStores.get(groupPosition).isEditing()) {
            if (cartItem.getGood().getGoodStatus() == 0 ||
                    cartItem.getGood().getGoodSkus().get(0).getStockNumber() <= 0) {
                childViewHolder.amountView.setVisibility(View.INVISIBLE);
                childViewHolder.tvTitle.setVisibility(View.VISIBLE);
                childViewHolder.tvNumber.setVisibility(View.INVISIBLE);
                childViewHolder.tvDesc.setVisibility(View.VISIBLE);
            } else {
                childViewHolder.amountView.setVisibility(View.VISIBLE);
                childViewHolder.tvTitle.setVisibility(View.INVISIBLE);
                childViewHolder.tvNumber.setVisibility(View.INVISIBLE);
                childViewHolder.tvDesc.setVisibility(View.INVISIBLE);
            }
//            childViewHolder.ivDelete.setVisibility(View.VISIBLE);

        } else {
            if (cartItem.getGood().getGoodStatus() == 0 ||
                    cartItem.getGood().getGoodSkus().get(0).getStockNumber() <= 0) {
                childViewHolder.tvNumber.setVisibility(View.INVISIBLE);
            } else {
                childViewHolder.tvNumber.setVisibility(View.VISIBLE);
            }
            childViewHolder.amountView.setVisibility(View.GONE);
//            childViewHolder.ivDelete.setVisibility(View.GONE);
            childViewHolder.tvTitle.setVisibility(View.VISIBLE);
            childViewHolder.tvDesc.setVisibility(View.VISIBLE);
        }

        childViewHolder.amountView.setCurrentAmount(cartItem.getNum());
        // 库存量
        childViewHolder.amountView.setGoods_storage(1000);
        childViewHolder.amountView.setOnAmountChangeListener(new AmountView.OnAmountChangeListener() {
            @Override
            public void onAmountChange(View view, final int amount) {
                if (amount <= 0) {
                    return;
                }
                HashMap<String, String> map = new HashMap<>();
                map.put("userId", EnvironmentVariable.getUserName());
                try {
                    JSONArray jsonArray = new JSONArray();
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put("goodbh", cartItem.getGood().getGoodId());
                    jsonObject.put("goodNum", amount);
                    jsonObject.put("skuId", cartItem.getGood().getGoodSkus().get(0).getSkuId());
                    jsonArray.put(jsonObject);
                    map.put("goods", jsonArray.toString());
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                MallRequestUtil.getRequest(mContext.getClass().getSimpleName(), CART_ADD_OR_DELETE_URL, map, new MallRequestUtil.MallRequestCallback() {
                    @Override
                    public void onSuccess(String response) {
                        cartItem.setNum(amount);//先这样解决
                        dealPrice();
                        EventBus.getDefault().post(new UpdateCartBadgeEvent());
                    }

                    @Override
                    public void onFail(String error) {

                    }
                });
            }
        });
//        childViewHolder.ivDelete.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View view) {
//                new AlertDialog.Builder(mContext).setMessage("是否要将这件商品删除？")
//                        .setPositiveButton(@string/common_text_confirm, new DialogInterface.OnClickListener() {
//
//                            @Override
//                            public void onClick(DialogInterface dialog, int which) {
//                                dialog.dismiss();
//                                HashMap<String, String> map = new HashMap<>();
//                                map.put("userId", EnvironmentVariable.getProperty(Constants.CHAT_USER_ID));
//                                try {
//                                    JSONArray jsonArray = new JSONArray();
//                                        JSONObject jsonObject = new JSONObject();
//                                        jsonObject.put("goodbh", cartItem.getItemId());
//                                        jsonObject.put("goodNum", 0);
//                                        jsonArray.put(jsonObject);
//                                    map.put("goods", jsonArray.toString());
//                                } catch (JSONException e) {
//                                    e.printStackTrace();
//                                }
//
//                                MallRequestUtil.getCartRequest(mContext, "addOrRemoveGood", map, new MallRequestUtil.MallRequestCallback() {
//                                    @Override
//                                    public void onSuccess(String response) {
//                                        onAmountChangeListener.onAmountChange();
//                                        dealPrice();
//                                        EventBus.getDefault().post(new UpdateCartBadgeEvent());
//                                    }
//
//                                    @Override
//                                    public void onFail(String error) {
//
//                                    }
//                                });
//
//                            }
//                        }).setNegativeButton(R.string.common_text_cancel, new DialogInterface.OnClickListener() {
//                    @Override
//                    public void onClick(DialogInterface dialog, int which) {
//                        dialog.dismiss();
//                    }
//                }).show();
//            }
//        });
        if (cartItem.getGood().getGoodSkus() != null && cartItem.getGood().getGoodSkus().size() > 0) {
            List<GoodSkusBean.AttributeContentListBean> attrList = cartItem.getGood().getGoodSkus().get(0).getAttributeContentList();
            StringBuilder stringBuilder = new StringBuilder();
            for (int j = 0; j < attrList.size(); j++) {
                stringBuilder.append(attrList.get(j).getVIdName())
                        .append("；");
            }
            stringBuilder.deleteCharAt(stringBuilder.length() - 1);
            childViewHolder.tvDesc.setText(stringBuilder);
            childViewHolder.tvPrice.setText("￥" + TCMathUtil.retainAsignDecimalsWithZero(cartItem.getGood().getGoodSkus().get(0).getSkuPrice(), 2));
            childViewHolder.tvTitle.setText(cartItem.getGood().getGoodSkus().get(0).getPropertiesName());
        } else {
            childViewHolder.tvDesc.setText(cartItem.getGood().getDescription());
            childViewHolder.tvPrice.setText("￥" + TCMathUtil.retainAsignDecimalsWithZero(cartItem.getGood().getMallGoodPrice().getPrice(), 2));
            childViewHolder.tvTitle.setText(cartItem.getGood().getGoodName());
        }
        childViewHolder.tvNumber.setText("x" + cartItem.getNum());
        Glide.with(mContext)
                .load(cartItem.getGood().getGoodCover())
                .apply(new RequestOptions().fitCenter()
                        .diskCacheStrategy(DiskCacheStrategy.ALL)
                        .skipMemoryCache(false))
                .into(childViewHolder.ivImg);
        final boolean nowChecked = cartItem.isSelect();
        childViewHolder.itemCheck.setChecked(nowChecked);
        childViewHolder.itemCheck.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                cartItem.setSelect(!nowChecked);
                boolean isOneParentAllChildIsChecked = dealOneParentAllChildIsChecked(groupPosition);
                CartListBean.MyshopcartBean storeBean = cartStores.get(groupPosition);
                storeBean.setSelect(isOneParentAllChildIsChecked);
                onAllCheckedBoxNeedChangeListener.onCheckedBoxNeedChange(dealAllParentIsChecked());
                notifyDataSetChanged();
                dealPrice();
            }
        });
        return view;
    }

    @Override
    public boolean isChildSelectable(int i, int i1) {
        return true;
    }

    private void setupOneParentAllChildChecked(boolean isChecked, int groupPosition) {

        CartListBean.MyshopcartBean storeBean = cartStores.get(groupPosition);
        storeBean.setSelect(isChecked);

        List<CartListBean.MyshopcartBean.GoodsBean> childMapList = cartStores.get(groupPosition).getGoods();
        for (int j = 0; j < childMapList.size(); j++) {
            CartListBean.MyshopcartBean.GoodsBean goodsBean = childMapList.get(j);
            if (goodsBean.getGood().getGoodStatus() == 1 && goodsBean.getGood().getGoodSkus().get(0).getStockNumber() > 0) {
                goodsBean.setSelect(isChecked);
            }
        }
        notifyDataSetChanged();
        dealPrice();
    }

    public boolean dealAllParentIsChecked() {

        for (int i = 0; i < cartStores.size(); i++) {
            CartListBean.MyshopcartBean storeBean = cartStores.get(i);
            if (!storeBean.isSelect()) {
                return false;//如果有一个没选择  就false
            }
        }
        return true;
    }

    public boolean dealOneParentAllChildIsChecked(int groupPosition) {

        // StoreBean storeBean= (StoreBean) parentMapList.get(groupPosition).get("parentName");
        List<CartListBean.MyshopcartBean.GoodsBean> childMapList = cartStores.get(groupPosition).getGoods();
        for (int j = 0; j < childMapList.size(); j++) {
            CartListBean.MyshopcartBean.GoodsBean goodsBean = childMapList.get(j);
            if (!goodsBean.isSelect() &&
                    (goodsBean.getGood().getGoodStatus() == 1 &&
                            goodsBean.getGood().getGoodSkus().get(0).getStockNumber() > 0)) {
                return false;//如果有一个没选择  就false
            }
        }
        return true;
    }

    public void dealPrice() {
        // showList();
        totalCount = 0;
        totalPrice = 0.00;
        totalTax = 0.00;
        List<CartListBean.MyshopcartBean.GoodsBean> cartItems = new ArrayList<>();
        for (int i = 0; i < cartStores.size(); i++) {
            //StoreBean storeBean= (StoreBean) parentMapList.get(i).get("parentName");

            List<CartListBean.MyshopcartBean.GoodsBean> childMapList = cartStores.get(i).getGoods();
            for (int j = 0; j < childMapList.size(); j++) {
                CartListBean.MyshopcartBean.GoodsBean goodsBean = childMapList.get(j);
                int count = Integer.valueOf(goodsBean.getNum());
                double price = Double.valueOf(goodsBean.getGood().getGoodSkus().get(0).getSkuPrice());
                double tax;
                if (goodsBean.isSelect()) {
                    totalCount += count;//单品多数量只记1
                    totalPrice = MyMathUtil.add(totalPrice, MyMathUtil.mul(price, count));
                    cartItems.add(goodsBean);
                }

            }
        }
        onGoodsDeleteChangeListener.onGoodsDeleteChange(cartItems);
        //计算回调
        onGoodsCheckedChangeListener.onGoodsCheckedChange(totalCount, totalPrice, totalTax, cartItems);
    }

    public void setupAllChecked(boolean isChecked) {

        for (int i = 0; i < cartStores.size(); i++) {
            CartListBean.MyshopcartBean storeBean = cartStores.get(i);
            storeBean.setSelect(isChecked);

            List<CartListBean.MyshopcartBean.GoodsBean> childMapList = storeBean.getGoods();
            for (int j = 0; j < childMapList.size(); j++) {
                CartListBean.MyshopcartBean.GoodsBean goodsBean = childMapList.get(j);
                if (goodsBean.getGood().getGoodStatus() == 1 && goodsBean.getGood().getGoodSkus().get(0).getStockNumber() > 0) {
                    goodsBean.setSelect(isChecked);
                }
            }
        }
        notifyDataSetChanged();
        dealPrice();
    }

    /**
     * 判断商店里的商品是不是全部无效
     */
    private boolean isShopItemAllInvalid(int groupPosition) {
        List<CartListBean.MyshopcartBean.GoodsBean> childMapList = cartStores.get(groupPosition).getGoods();
        for (int j = 0; j < childMapList.size(); j++) {
            CartListBean.MyshopcartBean.GoodsBean goodsBean = childMapList.get(j);
            if (goodsBean.getGood().getGoodStatus() == 1 && goodsBean.getGood().getGoodSkus().get(0).getStockNumber() > 0) {
                 return false;
            }
        }
        return true;
    }

    public boolean isAllGoodInvalid() {
        for (int i = 0; i < cartStores.size(); i++) {
            CartListBean.MyshopcartBean storeBean = cartStores.get(i);
            if (!isShopItemAllInvalid(i)) {
                return false;
            }
        }
        return true;
    }

    public interface OnAdapterAmountChangeListener {
        void onAmountChange();
    }

    public void setOnAmountChangeListener(OnAdapterAmountChangeListener onAmountChangeListener) {
        this.onAmountChangeListener = onAmountChangeListener;
    }

    public interface OnAllCheckedBoxNeedChangeListener {
        void onCheckedBoxNeedChange(boolean allParentIsChecked);
    }

    public interface OnEditingTvChangeListener {
        void onEditingTvChange(boolean allIsEditing);
    }

    public interface OnGoodsCheckedChangeListener {
        void onGoodsCheckedChange(int totalCount, double totalPrice, double totalTax, List<CartListBean.MyshopcartBean.GoodsBean> checkItems);
    }

    public interface OnCheckHasGoodsListener {
        void onCheckHasGoods(boolean isHasGoods);
    }

    public interface OnGoodsDeleteChangeListener {
        void onGoodsDeleteChange(List<CartListBean.MyshopcartBean.GoodsBean> cartItems);
    }

    public void setOnGoodsDeleteChangeListener(OnGoodsDeleteChangeListener onGoodsDeleteChangeListener) {
        this.onGoodsDeleteChangeListener = onGoodsDeleteChangeListener;
    }

    public void setOnCheckHasGoodsListener(OnCheckHasGoodsListener onCheckHasGoodsListener) {
        this.onCheckHasGoodsListener = onCheckHasGoodsListener;
    }

    public void setOnEditingTvChangeListener(OnEditingTvChangeListener onEditingTvChangeListener) {
        this.onEditingTvChangeListener = onEditingTvChangeListener;
    }

    public void setOnGoodsCheckedChangeListener(OnGoodsCheckedChangeListener onGoodsCheckedChangeListener) {
        this.onGoodsCheckedChangeListener = onGoodsCheckedChangeListener;
    }

    public void setOnAllCheckedBoxNeedChangeListener(OnAllCheckedBoxNeedChangeListener onAllCheckedBoxNeedChangeListener) {
        this.onAllCheckedBoxNeedChangeListener = onAllCheckedBoxNeedChangeListener;
    }

    class GroupViewHolder {
        TextView storeName;
        CheckBox storeCheck;
        ImageView ivShopIcon;
    }

    class ChildViewHolder {
        ImageView ivImg;
        TextView tvTitle;
        TextView tvPrice;
        TextView tvNumber;
        //        TextView benefit;
        CheckBox itemCheck;
        AmountView amountView;
        TextView tvDesc;
        View invalidLayer;
        TextView tvInvalid;
    }
}
